// AppointmentServiceImpl.java（修改后）
package com.hy.heath.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hy.heath.common.BusinessException;
import com.hy.heath.mapper.AppointmentMapper;
import com.hy.heath.pojo.entity.Appointment;
import com.hy.heath.service.AppointmentService;
import com.hy.heath.service.DoctorService;
import com.hy.heath.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class AppointmentServiceImpl extends ServiceImpl<AppointmentMapper, Appointment> implements AppointmentService {

    @Autowired
    private UserService userService;

    @Autowired
    private DoctorService doctorService;

    @Override
    @Transactional
    public void createAppointment(Appointment appointment) {
        // 校验用户存在性
        if (userService.getById(appointment.getUserId()) == null) {
            throw new BusinessException("用户不存在");
        }

        // 校验医生存在性
        if (doctorService.getById(appointment.getDoctorId()) == null) {
            throw new BusinessException("医生不存在");
        }

        // 校验时间冲突（使用MP条件构造器）
        long conflictCount = this.count(new LambdaQueryWrapper<Appointment>()
                .eq(Appointment::getDoctorId, appointment.getDoctorId())
                .eq(Appointment::getAppointmentDate, appointment.getAppointmentDate())
                .eq(Appointment::getAppointmentTime, appointment.getAppointmentTime()));
        if (conflictCount > 0) {
            throw new BusinessException("该时间段医生已有预约，请选择其他时间");
        }

        // 设置默认状态
        if (appointment.getStatus() == null) {
            appointment.setStatus("待确认");
        }

        this.save(appointment);
    }

    @Override
    public Appointment getAppointment(Integer id) {
        return this.getById(id);
    }

    @Override
    @Transactional
    public void updateAppointment(Appointment appointment) {
        // 获取原始数据
        Appointment existing = this.getById(appointment.getAppointmentId());
        if (existing == null) {
            throw new BusinessException("预约记录不存在");
        }

        // 禁止修改关键字段
        if (!existing.getUserId().equals(appointment.getUserId()) ||
                !existing.getDoctorId().equals(appointment.getDoctorId())) {
            throw new BusinessException("禁止修改用户或医生信息");
        }

        // 状态合法性校验
        if (appointment.getStatus() != null &&
                !isValidStatusTransition(existing.getStatus(), appointment.getStatus())) {
            throw new BusinessException("非法的状态变更");
        }

        this.updateById(appointment);
    }

    // 状态转换校验逻辑保持不变
    private boolean isValidStatusTransition(String oldStatus, String newStatus) {
        return switch (oldStatus) {
            case "待确认" -> List.of("已确认", "已取消").contains(newStatus);
            case "已确认" -> List.of("已完成", "已取消").contains(newStatus);
            case "已完成", "已取消" -> false;
            default -> throw new BusinessException("未知的预约状态");
        };
    }
    // 可在ServiceImpl中添加更多MP增强方法
    public Page<Appointment> listByUser(Integer userId, Page<Appointment> page) {
        return this.page(page, new LambdaQueryWrapper<Appointment>()
                .eq(Appointment::getUserId, userId)
                .orderByDesc(Appointment::getCreatedAt));
    }
}